package com.atguigu.system.service.impl;

import com.atguigu.common.result.ResultCodeEnum;
import com.atguigu.model.system.SysUser;
import com.atguigu.system.custom.CustomUser;
import com.atguigu.system.execption.GuiguException;
import com.atguigu.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.util.ArrayUtils;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.getSysUserByUsername(username);

        if(sysUser == null){ //用户不存在
            throw new GuiguException(ResultCodeEnum.ACCOUNT_ERROR);
        }

        if(sysUser.getStatus() == 0){ // status = 0 禁用
            throw new GuiguException(ResultCodeEnum.ACCOUNT_STOP);
        }

        //默认空权限集合。暂时不查 TODO
        List<GrantedAuthority> authorities = Collections.emptyList();


        //根据用户id查询用户权限(按钮标识)集合
        List<String> userBtnPermsList = sysUserService.getUserBtnPermsByUserId(sysUser.getId());
        sysUser.setUserPermsList(userBtnPermsList);

        return new CustomUser(sysUser,authorities);
    }
}
